import os
import sys
import cv2 as cv
import json
import time
import numpy as np

print("init...")


IN_FILE = "in.jpg"
OUT_FILE = "out.json"

STATE_0 = "STATE_0.state"
STATE_IN_READY = "STATE_IN_READY.state"
STATE_RUNNING = "STATE_RUNNING.state"
STATE_OUT_READY = "STATE_OUT_READY.state"
STATE_ERROR = "STATE_ERROR.state"

STATES = [
    STATE_0,
    STATE_IN_READY,
    STATE_RUNNING,
    STATE_IN_READY,
    STATE_ERROR,
]


# 脸的侦测者
def face_detect(src):
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    face_detector = cv.CascadeClassifier(r"C:\haarcascade_frontalface_alt_tree.xml")
    faces = face_detector.detectMultiScale(gray, scaleFactor=1.005, minSize=(115, 115))
    cnt = 0
    # 返回数组
    r = []
    for x, y, w, h in faces:
        print(x, y, w, h)
        r.append(np.array([x, y, w, h]).tolist())
        cnt += 1
    print("侦测到了 %d 张脸！" % cnt)
    return r


def my_run():
    print("processing...")
    print(os.path.join(work_path, IN_FILE))
    if os.path.isfile(os.path.join(work_path, IN_FILE)) is True:
        my_img_path = os.path.join(work_path, IN_FILE)
        # with open(os.path.join(work_path, IN_FILE), 'r', encoding='utf-8') as f:
        my_img = cv.imread(my_img_path)
        print(my_img_path)
        print(os.path.isfile(my_img_path))
        # gray_img = cv.cvtColor(my_img, code=cv.COLOR_BGR2GRAY)

        print(os.path.join(work_path, OUT_FILE))
        lac_obj = face_detect(my_img)
        json_str = json.dumps(lac_obj, ensure_ascii=False)
        with open(os.path.join(work_path, OUT_FILE), 'w+', encoding='utf-8') as f:
            f.write(json_str)
    else:
        print("NO IN FILE")
        change_to(STATE_0)


    return


def get_state():
    for s in STATES:
        if os.path.isfile(os.path.join(work_path, s)) is True:
            return s


def change_to(state_str: str):
    print(state_str[0:-6])
    os.system(
        "REN %s %s" % (
            os.path.join(work_path, "%s" % get_state()),
            state_str
        )
    )


if __name__ == '__main__':

    if len(sys.argv) != 2:
        print("ERR: usage: run.py Running_path")
        os.system("pause")
        sys.exit(0)
    else:
        work_path = sys.argv[-1]
        print("Work Path \"%s\"" % work_path)

    if os.path.isdir(work_path) is False:
        print("ERR: path is not exited.")
        os.system("pause")
        sys.exit(0)

    print("Running...")

    os.system("del " + os.path.join(work_path, "*.state"))
    if (os.path.isfile(os.path.join(work_path, STATE_0))) is False:
        with open(os.path.join(work_path, STATE_0), "w+", encoding='utf-8') as f:
            pass

    while True:
        for my_str in STATES:
            if os.path.isfile(
                    os.path.join(work_path, STATE_IN_READY)
            ) is True:
                change_to(STATE_RUNNING)
                my_run()
                change_to(STATE_OUT_READY)
        time.sleep(0.5)
